package com.qjc.demo.algorithm;

/**
 * @ClassName: MidNodeLinkList
 * @Description: 找到链表的中间节点，如果有两个，则返回第二个中间接点
 * 1->2->3->4->5     中间节点是3
 * 1->2->3->4->5->6  中间节点是4
 * @Author: qjc
 * @Date: 2022/5/6 4:09 PM
 */
public class MidNodeLinkList {

    // 解题思路，利用快慢指针，快指针一次移动两步，慢指针一次移动一步
    // 直到快指针为null，或者其next==null，那么慢指针指向的就是中间节点，因为快指针移动速度是慢指针的两倍
    // 当有奇数个节点的时候，只有一个中间节点，慢指针指向的就是中间节点
    // 当有偶数个节点的时候，有两个中间节点，而慢指针刚好指向第二个中间节点，所以直接返回就行
    public static int midNode(MidNode head) {
        MidNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow.data;
    }

    public static void main(String[] args) {
        MidNode n1 = new MidNode(1);
        MidNode n2 = new MidNode(2);
        MidNode n3 = new MidNode(3);
        MidNode n4 = new MidNode(4);
        MidNode n5 = new MidNode(5);
        MidNode n6 = new MidNode(6);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        n6.next = null;

        System.out.println(midNode(n1));
    }

}

class MidNode {
    int data;
    MidNode next;

    public MidNode(int data) {
        this.data = data;
    }
}